import cv2
import os

# 从中间切分图像
def split_images_in_folder(folder_path):
    left_path = os.path.dirname(folder_path) + "/left"
    right_path = os.path.dirname(folder_path) + "/right"
    if not os.path.exists(left_path):
        os.makedirs(left_path)
    if not os.path.exists(right_path):
        os.makedirs(right_path)

    for filename in os.listdir(folder_path):
        if filename.endswith('.jpg') or filename.endswith('.png'):  # 检查文件是否为图像
            img = cv2.imread(os.path.join(folder_path, filename))
            if img is not None:
                h, w = img.shape[:2]
                left_img = img[:, :w//2]  # 获取左半部分的图像
                right_img = img[:, w//2:]  # 获取右半部分的图像
                cv2.imwrite(os.path.join(left_path, filename), left_img)  # 保存左半部分的图像
                cv2.imwrite(os.path.join(right_path, filename), right_img)  # 保存右半部分的图像

# 调整图像大小并裁剪
def resize_and_crop_images_in_folder(folder_path, size, save_path):
    for filename in os.listdir(folder_path):
        if filename.endswith('.jpg') or filename.endswith('.png'):  # 检查文件是否为图像
            img = cv2.imread(os.path.join(folder_path, filename))
            if img is not None:
                h, w = img.shape[:2]
                if w > h:  # 如果宽度大于高度
                    new_w = size[0]
                    new_h = int(h * new_w / w)
                else:  # 如果高度大于或等于宽度
                    new_h = size[1]
                    new_w = int(w * new_h / h)
                resized_img = cv2.resize(img, (new_w, new_h))  # 调整图像大小
                start_x = new_w//2 - size[0]//2
                start_y = new_h//2 - size[1]//2
                cropped_img = resized_img[start_y:start_y+size[1], start_x:start_x+size[0]]
                cv2.imwrite(os.path.join(save_path, filename), cropped_img)  # 保存图像到指定路径

# 预处理文件夹中的图像
def preprocess_images_in_folder(folder_path):
    split_images_in_folder(folder_path)
    left_path = os.path.dirname(folder_path) + "/left"
    right_path = os.path.dirname(folder_path) + "/right"
    left_save_path = os.path.dirname(folder_path) + "/preprocessed/left"
    right_save_path = os.path.dirname(folder_path) + "/preprocessed/right"
    if not os.path.exists(left_save_path):
        os.makedirs(left_save_path)
    if not os.path.exists(right_save_path):
        os.makedirs(right_save_path)

    # size = (854, 476)  # 调整后的图像尺寸
    size = (640, 360)  # 调整后的图像尺寸
    resize_and_crop_images_in_folder(left_path, size, left_save_path)
    resize_and_crop_images_in_folder(right_path, size, right_save_path)
    
def main():
    folder_path = u'D:/Users/XiangyeHuang/Pictures/xyz_platform_datas/biaoding/orig'  # 源文件夹路径
    size = (854, 476)  # 调整后的图像尺寸
    preprocess_images_in_folder(folder_path)

if __name__ == "__main__":
    main()